<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 普通卡片 -->
    <el-card class="box-card">
      <!-- 用户搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryData.query"
            clearable
            @clear="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="usersList" style="width: 100%" border stripe>
        <el-table-column type="index" width="50" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template v-slot="{ row }">
            <el-switch
              v-model="row.mg_state"
              @change="statusChange(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 编辑用户按钮 -->
          <template v-slot="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEdit(row)"
            ></el-button>
            <!-- 删除用户按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="showDeleteMessageBox(row.id)"
            ></el-button>
            <!-- 设置按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRolesDialog(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addUserDialogClose"
    >
      <el-form
        ref="addUserForm"
        :model="addUserForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 编辑表单 -->
      <el-form
        ref="editUserForm"
        :model="editUserForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 开始 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesDialogVisible"
      width="50%"
      @close="selectValue = ''"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <div class="selectBox">
          选择角色：
            <el-select v-model="selectValue" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoles"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配角色对话框 结束 -->
  </div>
</template>

<script>
export default {
  data() {
    // 定义验证邮箱的函数
    const checkEmail = (rule, value, callback) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    // 定义验证手机号的函数
    const checkMobile = (rule, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    return {
      usersList: [],
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      addDialogVisible: false,
      // 添加用户表单
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单校验规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑对话框显示与否
      editDialogVisible: false,
      // 编辑用户表单
      editUserForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 分配角色对话框
      setRolesDialogVisible: false,
      // 分配角色信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 角色下拉选择框选择的值
      selectValue: ''
    }
  },

  created() {
    this.getUsersList()
  },

  methods: {
    // 定义获取用户列表的函数
    async getUsersList() {
      const res = await this.$axios.get('/users', {
        params: this.queryData
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.usersList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(val) {
      this.queryData.pagesize = val
      this.getUsersList()
    },
    handleCurrentChange(val) {
      this.queryData.pagenum = val
      this.getUsersList()
    },
    // 修改用户状态
    async statusChange(row) {
      // console.log(row)
      const res = await this.$axios.put(`users/${row.id}/state/${row.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error('修改状态失败')
      }
      this.$message.success('修改状态成功')
    },
    // 关闭对话框的处理函数
    addUserDialogClose() {
      this.$refs.addUserForm.resetFields()
    },
    // 提交添加的用户
    addUserSubmit() {
      this.$refs.addUserForm.validate(async (flag, obj) => {
        if (!flag) return
        const res = await this.$axios.post('/users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.addDialogVisible = false
        this.getUsersList()
      })
    },
    // 处理编辑用户逻辑
    showEdit(row) {
      this.editDialogVisible = true
      // const editUserForm = this.editUserForm
      // this.editUserForm.username = username
      // this.editUserForm.email = email
      // this.editUserForm.mobile = mobile
      for (const key in this.editUserForm) {
        this.editUserForm[key] = row[key]
      }
      this.editUserForm.id = row.id
      // console.log(id)
    },
    // 编辑对话框关闭时清空编辑表单
    editDialogClose() {
      this.$refs.editUserForm.resetFields()
    },
    // 处理提交编辑用户
    editUserSubmit() {
      this.$refs.editUserForm.validate(async flag => {
        if (!flag) return
        const res = await this.$axios.put('/users/' + this.editUserForm.id, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('编辑用户失败')
        }
        this.$message.success('编辑用户成功')
        this.editDialogVisible = false
        this.getUsersList()
      })
    },
    // 弹出确认删除消息提示框
    showDeleteMessageBox(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$axios.delete('users/' + id)
          if (res.meta.status !== 200) {
            this.$message.error('删除用户失败')
          }
          this.getUsersList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击设置
    async showSetRolesDialog(row) {
      this.userInfo = row
      // 获取角色列表
      const res = await this.$axios.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.$message.success('获取角色列表成功')
      this.rolesList = res.data
      this.setRolesDialogVisible = true
    },
    // 点击分配角色对话框的确定
    async setRoles() {
      if (this.selectValue === '') {
        return this.$message.error('请选择角色')
      }
      const id = this.userInfo.id
      const rid = this.selectValue
      const res = await this.$axios.put(`users/${id}/role`, {
        rid
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.getUsersList()
      this.setRolesDialogVisible = false
    }
  }
}
</script>

<style scoped lang='less'>
.selectBox {
  margin-top: 8px;
  padding-left: 50px;
}
.el-dialog {
  p + p {
    margin-top: 8px;
  }
  p {
    padding-left: 50px;
  }
}
</style>
